import {fetchUserMsgReq, fetchMsgStateReq, fetchSysMsgReq, fetchVipMsgReq,} from "../apis/goApis";
import {handleResp} from "../utils/commonfunc";
import LocalStorageService from "../utils/LocalStorageService";

export const msg = {
    state: {
        msgState: [0, 0, 0,],
        msg: {
            sys: [],
            vip: [],
            user: [],
        }
    },

    reducers: {
        setMsgState(state, payload) {
            const msgState = payload.msgState
            return {
                ...state,
                msgState,
            }
        },

        setMsg(state, payload) {
            const key = payload.key
            const list = payload.list.reverse()
            const old = state.msg[key]
            return {
                ...state,
                msg: {
                    ...state.msg,
                    [key]: [...list, ...old],
                }
            }
        }
    },

    effects: (dispatch) => ({
        async doFetchMsgState(payload, rootState) {
            const resp = await fetchMsgStateReq(payload)
            handleResp(resp, dispatch, (data) => {
                // console.log(data)
                const msgState = data.ok
                const userDetail = rootState.user.userdetail
                const flag = userDetail.initFlag
                const Vip = userDetail.Vip
                if (flag === 0 || Vip === 0) {
                    msgState[1] = 0
                }
                dispatch.msg.setMsgState({msgState,})
            })
        },

        async doFetchMsg(payload) {
            const type = payload.type
            const respM = {
                'vip': fetchVipMsgReq,
                'sys': fetchSysMsgReq,
                'user': fetchUserMsgReq,
            }
            const resp = await respM[type]({uid: payload.uid,})
            handleResp(resp, dispatch, (data) => {
                try {
                    const list = data.ok.map(item => JSON.parse(item))
                    const end = data.end
                    if (end === undefined) {
                        dispatch.msg.setMsg({list, key: type,})
                        this.doFetchMsgState({uid: LocalStorageService.get('userid')})
                    } else {
                        if (end === true) {
                            dispatch.msg.setMsg({list, key: type,})
                            this.doFetchMsgState({uid: LocalStorageService.get('userid')})
                        } else {
                            dispatch.msg.setMsg({list, key: type,})
                            this.doFetchMsg(payload)
                        }
                    }
                } catch (e) {
                    return
                }

            })
        },
    }),
}
